﻿using System;
using UnityEngine;

[ExecuteInEditMode]
public class LazyInstance : MonoBehaviour
{
    [HideInInspector]
    public Bounds bounds;
    private static VisibilityListener m_visibilityListenerPrefab;
    private static Mesh m_visibilityMesh;
    public GameObject prefab;

    protected virtual void Awake()
    {
        if (Application.isPlaying)
        {
            VisibilityListener listener = UnityEngine.Object.Instantiate<VisibilityListener>(visibilityListenerPrefab);
            listener.onBecameVisible = new Action(this.OnBecameVisible);
            Transform transform = listener.transform;
            transform.parent = base.transform;
            transform.localPosition = this.bounds.center;
            transform.localScale = this.bounds.size;
        }
    }

    private void OnBecameVisible()
    {
        if (Application.isPlaying)
        {
            Transform transform = UnityEngine.Object.Instantiate<GameObject>(this.prefab).transform;
            Transform transform2 = base.transform;
            transform.position = transform2.position;
            transform.eulerAngles = transform2.eulerAngles;
            transform.localScale = transform2.localScale;
            transform.parent = transform2.parent;
            UnityEngine.Object.Destroy(base.gameObject);
        }
    }

    public static VisibilityListener visibilityListenerPrefab
    {
        get
        {
            if (m_visibilityListenerPrefab == null)
            {
                GameObject obj2 = new GameObject("visibilityListener") {
                    hideFlags = HideFlags.HideAndDontSave
                };
                obj2.AddComponent<MeshFilter>().sharedMesh = visibilityMesh;
                obj2.AddComponent<MeshRenderer>();
                m_visibilityListenerPrefab = obj2.AddComponent<VisibilityListener>();
            }
            return m_visibilityListenerPrefab;
        }
    }

    public static Mesh visibilityMesh
    {
        get
        {
            if (m_visibilityMesh == null)
            {
                m_visibilityMesh = new Mesh();
                m_visibilityMesh.vertices = new Vector3[] { new Vector3(-0.5f, -0.5f, -0.5f), new Vector3(0.5f, -0.5f, -0.5f), new Vector3(0.5f, 0.5f, -0.5f), new Vector3(-0.5f, 0.5f, -0.5f), new Vector3(-0.5f, -0.5f, 0.5f), new Vector3(0.5f, -0.5f, 0.5f), new Vector3(0.5f, 0.5f, 0.5f), new Vector3(-0.5f, 0.5f, 0.5f) };
                m_visibilityMesh.RecalculateBounds();
            }
            return m_visibilityMesh;
        }
    }
}

